// i.r(t), i.d(t, { default: () => ScreenshotsModule })
import Module from "./Module"
import SymbolList from "../SymbolList"
import SettingsModule from "./SettingsModule"
import CanvasData from "../data/CanvasData"
import browserUtil from "../utils/browser.util"
import { createBlob, encodeRenderTarget } from "../utils/jpg.util"
import Logger from "../utils/Logger"
import * as THREE from "three"
import RenderToTextureModule from "./RenderToTextureModule"
import { RequestRenderTargetCommand } from "../command/render.command"

const b = new Logger("screenshots")
export default class ScreenshotsModule extends Module {
  capturer: ScreenCapturer
  engine: any
  settingsModule: any
  canvas: any
  renderer: any
  renderToTexture: any
  renderTarget: any
  constructor() {
    super(...arguments), (this.name = "screenshots-module"), (this.capturer = new ScreenCapturer())
  }
  async init(e, t) {
    ;(this.engine = t),
      ([this.settingsModule, this.canvas, this.renderer, this.renderToTexture] = await Promise.all([
        t.getModule(SettingsModule),
        t.market.waitForData(CanvasData),
        t.getModuleBySymbol(SymbolList.WEBGL_RENDERER),
        t.getModule(RenderToTextureModule)
      ]))
  }
  async takeAndDownloadScreenshot(e, t, i) {
    this.renderTarget || (this.renderTarget = await this.engine.commandBinder.issueCommandWhenBound(new RequestRenderTargetCommand()))
    const n = await this.capturer.capture(i, e, this.renderer, this.renderToTexture, this.renderTarget)
    browserUtil.clickDown(createBlob(n), t)
  }
}
class ScreenCapturer {
  captureCamera: THREE.Camera
  constructor() {
    this.captureCamera = new THREE.Camera()
  }
  async capture(e, t, i, n, s) {
    const { camera: r, scene: o } = i.getScene()
    return (
      r.getWorldPosition(this.captureCamera.position),
      r.getWorldQuaternion(this.captureCamera.quaternion),
      this.captureCamera.projectionMatrix.copy(r.projectionMatrix),
      (this.captureCamera.layers.mask = e.mask),
      s.setSize(t.width, t.height),
      n.render(s.target, o, this.captureCamera),
      await encodeRenderTarget(s)
    )
  }
}
